export default {
  name: 'SMenu',
  props: {
    // 菜单数据
    menu: {
      type: Array,
      required: true
    },
    // 菜单主题 dark, light
    theme: {
      type: String,
      required: false,
      default: 'dark'
    },
    // 菜单模型 垂直 vertical,vertical-right 水平：horizontal, 内嵌:inline
    mode: {
      type: String,
      required: false,
      default: 'inline'
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data () {
    return {
      openKeys: [],
      selectedKeys: [],
      cachedOpenKeys: [],
      // vue 创建元素函数
      createElement:null,
    }
  },
  computed: {
    rootSubmenuKeys: vm => {
      const keys = []
      vm.menu.forEach(item => keys.push(item.path))
      return keys
    }
  },
  mounted () {
    this.updateMenu()
  },
  watch: {
    collapsed (val) {
      if (val) {
        this.cachedOpenKeys = this.openKeys.concat()
        this.openKeys = []
      } else {
        this.openKeys = this.cachedOpenKeys
      }
    },
    $route: function () {
      this.updateMenu()
    },
  },
  methods: {
    // 菜单展开或关闭事件处理
    onOpenChange (openKeys=[]) {
      if(openKeys.length == 1 && openKeys[0] == ''){
        // bug 当打开后关闭的key 是 空串时不处理，出现原因:路由数组:
        return;
      }
      // 在水平模式下时执行，并且不再执行后续
      if (this.mode === 'horizontal') {
        this.openKeys = openKeys
        return
      }
      // 非水平模式时， 关闭其他子菜单，开启子菜单
      const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key))
      if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
        this.openKeys = openKeys
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    },
    updateMenu () {
      const routes = this.$route.matched.concat()
      const { hidden } = this.$route.meta
      if (routes.length >= 3 && hidden=='TRUE') {
        routes.pop()
        this.selectedKeys = [routes[routes.length - 1].path]
      } else {
        this.selectedKeys = [routes.pop().path]
      }
      const openKeys = []
      if (this.mode === 'inline') {
        routes.forEach(item => {
          openKeys.push(item.path)
        })
      }
      this.collapsed ? (this.cachedOpenKeys = openKeys) : (this.openKeys = openKeys);
      
    },

    // render 菜单
    renderItem (menu) {
      if (menu.hidden != 'TRUE') {
        return (menu.children && menu.children.length>0)? this.renderSubMenu(menu) : this.renderMenuItem(menu)
      }
      return null
    },
    // 渲染菜单项
    renderMenuItem (menu) {
      const target = menu.meta.target || null
      const tag = target && 'a' || 'router-link'
      let props = { to: { name: menu.name } }
      if(menu.routeFlag && menu.routeFlag === 'TRUE'){
        props = { to: { path: menu.path } }
      }

      const attrs = { href: menu.path, target: menu.meta.target }

      return  this.createElement('AMenuItem',{props:{key:menu.path},key:menu.path},
        [
          this.createElement(tag,{props:{...props}, attrs},[
            this.renderIcon(menu.meta.icon),
            this.createElement('span',menu.meta.title)
          ])
        ]);
    },
    renderSubMenu (menu) {
      const itemArr = []

      menu.children.forEach(item => itemArr.push(this.renderItem(item)))

      return  this.createElement('ASubMenu',
        {
          key:menu.path,
          props: {
            key:menu.path,
            title:this.createElement(
              'span',
              {
                props:{},
                attr:{'slot':"title"},
                on:{
                  click:()=>{if(menu.redirect)this.$router.push({path:menu.redirect})}
                }
              },
              [
                this.renderIcon(menu.meta.icon),
                this.createElement('span',menu.meta.title)
              ])
          }
        },
        [
          itemArr
        ]);
    },
    renderIcon (icon) {
      if (icon === 'none' || !icon) {
        return this.createElement("a-icon", {props:{type:'menu'}});
      }
      const props = {}
      typeof (icon) === 'object' ? props.component = icon : props.type = icon;
      return this.createElement("a-icon", {props});
    }
  },

  // render 函数
  render (createElement) {
    this.createElement = createElement;
    const { mode, theme, menu } = this
    const props = {
      mode: mode,//  菜单模型 垂直 vertical,vertical-right 水平：horizontal, 内嵌:inline
      theme: theme,// 主题颜色 light dark
      openKeys: this.openKeys,// 当前展开的菜单项
      selectedKeys:this.selectedKeys // 当前选中的菜单项 key 数组
    }
    const on = {
      select: obj => {

        this.selectedKeys = obj.selectedKeys;
        this.$emit('select', obj)
      },
      openChange: this.onOpenChange
    }
    // 删除配置中隐藏的菜单，并且过滤为空的
    const menuTree = menu.map(item => {
      if (item.hidden==='TRUE') {
        return null
      }
      // 生成顶级菜单
      return this.renderItem(item)
    }).filter(t=>t);

    // 创建菜单对象
    return this.createElement("AMenu",{props, on:on, },[menuTree]);
  }
}
